<template>
  <transition name="van-fade">
    <div v-show="step === 0 || step === 1" :class="['main', step === 1 && 'show']">
      <img class="main_bg" src="/src/assets/test/home_bg.png" alt="">
      <div :class="['container', step === 1 && 'show']">
        <img class="cont" src="/src/assets/test/home_bg1.png"/>
        <div class="footer" @click="onFirstLink">
          进入测验
        </div>
      </div>
    </div>
  </transition>
  <audio ref="audioRef" loop="" src="/src/assets/test/bg.mp3"></audio>
  <div v-show="step === 2" class="page step1 flex_c">
    <div class="" style="min-height: 570px">
      <div class="txt">{{ step2Info.txt }}</div>
      <template v-if="step2Info.isShowInput">
        <div class="desc">
          Hi，该怎么称呼你？
        </div>
        <div class="input_box">
          <input type="text" ref="userName" @focus="userFocus" v-model="step2Info.userName" placeholder="请输入你的昵称">
        </div>
      </template>
  
      <p v-if="step2Info.userName" class="btns" @click="step = 3">开始<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 14" width="52" height="14"><path fill="none" fill-rule="evenodd" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 13h50L38.22 1"></path></svg></p>
    </div>
    <div class="flex_b_c">
      <p class="opt" @click="onFirstBack">
        <!-- http://content.daylucky.cn/admin/image/pqwiwnkh0oqz4gp1abf4xl7k.png -->
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 27 10" width="27" height="10" fill="#000000"><path fill="none" fill-rule="evenodd" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M26 9H1l8.78-8"></path></svg>
        <span class="ml-10">返回</span>
      </p>
      <p class="opt flex_a_c" @click="onPlay">
        <span class="mr-10">音乐：{{ !isPlay  ? '开' : '关' }}</span>
        <!-- http://content.daylucky.cn/admin/image/owawfbdtx1yoz0tvqq87vx50.png -->
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 19" width="22" height="19" fill="#000000" style="margin-top: 1px;"><path fill-rule="evenodd" d="M19.024 1.015a.5.5 0 0 1 0 .707L2.761 17.985a.5.5 0 0 1-.707-.707L18.317 1.015a.5.5 0 0 1 .707 0M13.88 4 3.878 14H1.5a1.5 1.5 0 1 1 0-3H4V6a2 2 0 0 1 2-2zm3.595.649C17.8 5.005 18 5.479 18 6v5h2.5a1.5 1.5 0 0 1 0 3H8.121z"></path></svg>
      </p>
    </div>
  </div>
  <div v-show="step === 3" class="page step2">
    <div class="background_id">Q{{ active }}</div>
    <div class="percent_root">
      <div class="percent_slot"></div>
      <div  class="percent_bar" :style="{ 'margin-top': `calc(${(Math.round(active * (100 / scoreList.length )) - 100) * 1}vh)` }"></div>
      <div class="percent_label">
        <span>{{ Math.round(active * (100 / scoreList.length))}}％</span>
        <!-- <span class="percent_text"></span> -->
      </div>
    </div>
    <div class="desc">
      <div class="title">{{ scoreList[active - 1].question }}</div>
      <div v-show="active === 1" class="txt">
        <svg  width="16px" height="15px"  viewBox="0 0 16 15" class="www-ssr-xcfb8h-star">
          <defs> 
            <radialGradient id="Star_2_svg__a" cx="50%" cy="11.817%" r="71.571%" fx="50%" fy="11.817%">
              <stop offset="0%" stop-color="#FFFFF1"></stop><stop offset="71.441%" stop-color="#FDDE3F"></stop><stop offset="100%" stop-color="#EE9F15"></stop>
            </radialGradient>
            <filter id="Star_2_svg__c" width="96.2%" height="92.7%" x="1.9%" y=".1%" filterUnits="objectBoundingBox">
              <feGaussianBlur in="SourceAlpha" result="shadowBlurInner1" stdDeviation="0.5"></feGaussianBlur>
              <feOffset dy="-1" in="shadowBlurInner1" result="shadowOffsetInner1"></feOffset>
              <feComposite in="shadowOffsetInner1" in2="SourceAlpha" k2="-1" k3="1" operator="arithmetic" result="shadowInnerInner1"></feComposite>
              <feColorMatrix in="shadowInnerInner1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"></feColorMatrix>
            </filter>
            <path id="Star_2_svg__b" d="m83.535 205.745-3.032 1.593a1 1 0 0 1-1.45-1.054l.578-3.375a1 1 0 0 0-.287-.885l-2.453-2.39a1 1 0 0 1 .555-1.707l3.389-.492a1 1 0 0 0 .753-.547l1.515-3.071a1 1 0 0 1 1.794 0l1.515 3.071a1 1 0 0 0 .753.547l3.39.492a1 1 0 0 1 .554 1.706l-2.453 2.39a1 1 0 0 0-.287.886l.579 3.375a1 1 0 0 1-1.451 1.054l-3.032-1.593a1 1 0 0 0-.93 0"></path>
          </defs>
          <g fill="none" fill-rule="evenodd" transform="translate(-76 -193)">
            <use xlink:href="#Star_2_svg__b" fill="url(#Star_2_svg__a)"></use>
            <use xlink:href="#Star_2_svg__b" fill="#000" filter="url(#Star_2_svg__c)"></use>
            <use xlink:href="#Star_2_svg__b" stroke="#FCC34E" stroke-width="0.5"></use>
          </g>
        </svg>
        <span>答题小提醒：</span>
        <br />
        <span>回答时，可以想着某段特定的关系、对象，以自己在关系中实际互动的情形回答</span>
      </div>
    </div>
    <div class="select_root flex_between">
      <div class="select_hr"></div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(1)"><div :class="['select_icon', result[active] === 1 && 'on']"></div></button>
        <div class="select_txt">非常不赞成</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(2)"><div :class="['select_icon', result[active] === 2 && 'on']"></div></button>
        <div class="select_txt">比较不赞成</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(3)"><div :class="['select_icon', result[active] === 3 && 'on']"></div></button>
        <div class="select_txt">有点不赞成</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(4)"><div :class="['select_icon', result[active] === 4 && 'on']"></div></button>
        <div class="select_txt">不确定</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(5)"><div :class="['select_icon', result[active] === 5 && 'on']"></div></button>
        <div class="select_txt">有点赞成</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(6)"><div :class="['select_icon', result[active] === 6 && 'on']"></div></button>
        <div class="select_txt">比较赞成</div>
      </div>
      <div class="select_label flex_c flex_align">
        <button class="select_btn flex_center" type="button" @click="onChooseResult(7)"><div :class="['select_icon', result[active] === 7 && 'on']"></div></button>
        <div class="select_txt">非常赞成</div>
      </div>
    </div>
    <div class="flex_b_c mt-72">
      <p class="opt" @click="onStep2Back">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 27 10" width="27" height="10" fill="#000000"><path fill="none" fill-rule="evenodd" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M26 9H1l8.78-8"></path></svg>
        <span class="ml-10">{{ active === 1 ? '返回' : '上一题' }}</span>
      </p>
      <p class="opt flex_a_c" @click="onPlay">
        <span class="mr-10">音乐：{{ !isPlay  ? '开' : '关' }}</span>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 19" width="22" height="19" fill="#000000" style="margin-top: 1px;"><path fill-rule="evenodd" d="M19.024 1.015a.5.5 0 0 1 0 .707L2.761 17.985a.5.5 0 0 1-.707-.707L18.317 1.015a.5.5 0 0 1 .707 0M13.88 4 3.878 14H1.5a1.5 1.5 0 1 1 0-3H4V6a2 2 0 0 1 2-2zm3.595.649C17.8 5.005 18 5.479 18 6v5h2.5a1.5 1.5 0 0 1 0 3H8.121z"></path></svg>
      </p>
    </div>
  </div>
  <div v-show="step === 4" class="page step3">
    <!-- <div v-show="!isPay" class="pt-42">
      <img src="http://content.daylucky.cn/admin/image/6wmob1twjqnhax2dea3ezih5.png" alt="" class="notice_gif">
      <div class="notice_txt">支付后查看你的依附角色.</div>
      <div class="pay_txt">需支付</div>
      <div class="pay_count">￥28.00</div>
      <div class="pay_btn" @click="onPayment">立即支付</div>
    </div> -->
    <div v-show="!isPay" class="pt-30" style="transition: opacity 800ms ease-in-out 0s; opacity: 1; z-index: 2;">
      <div class="fz-24 lh-32 pb-21 tc">你的依附角色即将现身...</div>
      <img class="notice_gif" src="/src/assets/test/loading.gif" alt="">
    </div>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { nextTick, ref, onMounted, toRefs, reactive  } from 'vue'
import { BigNumber } from 'bignumber.js'
import onPay from '@/utils/payment'
// import { scrollTo } from '@/utils/scrollTo'
let router = useRouter()
let step = ref(0)
let audioRef = ref('')
let active = ref(1)
let userName = ref('')
let maxVal = ref({ type: 0, value: 0})
let isPlay = ref(false)
onMounted(() => {
  prevLoad()
})
const getImageUrl = image => {
  // 参数一: 相对路径
  // 参数二: 当前路径的URL
  return new URL(`/src/assets/test/${image}`, import.meta.url).href
}
// 防止首页图片没加载完  导致卡顿无淡入效果
let prevLoad = () => {
  let count = 0
  let arr = [
    'home_bg.png',
    'home_bg1.png'
  ]
  arr.forEach(src => {
    let Img = new Image()
    Img.src = getImageUrl(src)
    Img.onload = (e) => {
      count++
      if (count === arr.length) {
        nextTick(() => {
          step.value = 1
        })
      }
    }
  })
}
let onPlay = () => {
   //如果暂停   点击即可播放
  if (audioRef.value.paused) {
    // 播放
    isPlay.value = true
    audioRef.value.play();
    //如果播放  点击暂停
  } else if (audioRef.value.play()) {
    //暂停
    isPlay.value = false
    audioRef.value.pause();
  }
}
let result = reactive({})
let scoreList = reactive([
  { id: 1, question: "总的来说,我不喜欢让恋人知道自己内心深处的感觉", reverseScored: false },
  { id: 2, question: "我担心我会被抛弃", reverseScored: false },
  { id: 3, question: "我觉得跟恋人亲近是一件惬意的事情", reverseScored: true },
  { id: 4, question: "我很担心我的恋爱关系", reverseScored: false },
  { id: 5, question: "当恋人开始要跟我亲近时,我发现我自己在退缩", reverseScored: false },
  { id: 6, question: "我担心恋人不会像我关心他(/她)那样地关心我", reverseScored: false },
  { id: 7, question: "当恋人希望跟我非常亲近时,我会觉得不自在", reverseScored: false },
  { id: 8, question: "我有点担心会失去恋人", reverseScored: false },
  { id: 9, question: "我觉得对恋人开诚布公,不是一件很舒服的事情", reverseScored: false },
  { id: 10, question: "我常常希望恋人对我的感情和我对恋人的感情一样强烈", reverseScored: false },
  { id: 11, question: "我想与恋人亲近,但我又总是会退缩不前", reverseScored: false },
  { id: 12, question: "我常常想与恋人形影不离,但有时这样会把恋人吓跑", reverseScored: false },
  { id: 13, question: "当恋人跟我过分亲密的时候,我会感到内心紧张", reverseScored: false },
  { id: 14, question: "我担心一个人独处", reverseScored: false },
  { id: 15, question: "我愿意把我内心的想法和感觉告诉恋人,我觉得这是一件自在的事情", reverseScored: true },
  { id: 16, question: "我想跟恋人非常亲密的愿望,有时会把恋人吓跑", reverseScored: false },
  { id: 17, question: "我试图避免与恋人变得太亲近", reverseScored: false },
  { id: 18, question: "我需要我的恋人一再地保证他/她是爱我的", reverseScored: false },
  { id: 19, question: "我觉得我比较容易与恋人亲近", reverseScored: true },
  { id: 20, question: "我觉得自己在要求恋人把更多的感觉,以及对恋爱关系的投入程度表现出来", reverseScored: false },
  { id: 21, question: "我发现让我依赖恋人,是一件困难的事情", reverseScored: false },
  { id: 22, question: "我并不是常常担心被恋人抛弃", reverseScored: true },
  { id: 23, question: "我倾向于不跟恋人过分亲密", reverseScored: false },
  { id: 24, question: "如果我无法得到恋人的注意和关心,我会心烦意乱或者生气", reverseScored: false },
  { id: 25, question: "我跟恋人什么事情都讲", reverseScored: true },
  { id: 26, question: "我发现恋人并不愿意像我所想的那样跟我亲近", reverseScored: false },
  { id: 27, question: "我经常与恋人讨论我所遇到的问题以及我关心的事情", reverseScored: true },
  { id: 28, question: "如果我还没有恋人的话,我会感到有点焦虑和不安", reverseScored: false },
  { id: 29, question: "我觉得依赖恋人是很自在的事情", reverseScored: true },
  { id: 30, question: "如果恋人不能像我所希望的那样在我身边时,我会感到灰心丧气", reverseScored: false },
  { id: 31, question: "我并不在意从恋人那里寻找安慰,听取劝告,得到帮助", reverseScored: true },
  { id: 32, question: "如果在我需要的时候,恋人却不在我身边,我会感到沮丧", reverseScored: false },
  { id: 33, question: "在需要的时候,我向恋人求助,是很有用的", reverseScored: true },
  { id: 34, question: "当恋人不赞同我时,我觉得确实是我不好", reverseScored: false },
  { id: 35, question: "我会在很多事情上向恋人求助,包括寻求安慰和得到承诺", reverseScored: true },
  { id: 36, question: "当恋人不花时间和我在一起时,我会感到怨恨", reverseScored: false}
])
let onChooseResult = val => {
  console.log(active.value, scoreList.length, result)
  let id = scoreList[active.value - 1].id
  result[id] = val
  if (active.value >= scoreList.length) {
    active.value = scoreList.length
    calculateECRScores()
    step.value = 4
    // setTimeout(() => {
    //   console.log(maxVal.value.type)
    //   router.replace('/test/result?type=' + maxVal.value.type)
    // }, 4000)
    return false
  } else if (active.value < scoreList.length){
    setTimeout(() => {
      ++active.value 
    }, 200)
  }
}
let userFocus = event => {
  // if (event.target && event.target.tagName === 'INPUT') {
    // 键盘弹出时，将页面内容向上滚动一定距离（例如50px）
    window.scrollTo({ top: 200, behavior: 'smooth' });
  // }
}
let onFirstBack = () => {
  step2Info.txt = ''
  step.value = 1
  audioRef.value.pause()
}
let onStep2Back = () => {
  if (active.value !== 1) {
    --active.value
  } else {
    --step.value
  }
}
let onFirstLink = () => {
  step.value = 2
  audioRef.value.play()
  isPlay.value = true
  setTimeout(() => {
    nextTick(() => {
      onEchoTxt()
    })
  }, 1000)
}
let step2Info = reactive({
  txt: '|',
  isShowInput: false,
  userName: ''
})
let onEchoTxt = () => {
  let txtArr = "总是在感情中过度付出?\n经常在开系中重蹈覆辙?\n\n让我们带着你\n透过心理学中经典的【依附理论】\n解锁自己的「依附角色」\n深入了解你在亲密关系里的模样\n\n作答题目时，可以想着现在/过去的特定对象，测验结果可能不同".split("")
  let len = 0
  let timer = setInterval(() => {
    step2Info.txt = step2Info.txt.slice(0, -1) + txtArr[len] + "|"
    if (len < txtArr.length - 1) {
      len += 1
    } else {
      step2Info.txt = step2Info.txt.slice(0, -1)
      clearInterval(timer)
      step2Info.isShowInput = true
      setTimeout(() => {
        nextTick(() => {
          userName.value.focus()
        })
      }, 100)

    }
  }, 100)
}

// 计算焦虑回避维度
let calculateECRScores = () => {
  let scores = {
    singularSum: 0,
    evenSum: 0
  }
  Object.keys(result).forEach((key) => {
    const isReverseScored = scoreList.find(({ id }) => key === id);
    let scoreVal = result[key]
    // 反向计分
    if (isReverseScored) {
      scoreVal = 7 - scoreVal + 1;
    }
    // 双数
    if (key % 2 === 0) {
      scores.evenSum += scoreVal
    } else {
      // 单数
      scores.singularSum += scoreVal
    }
  })
  /*
    * 判断类型
    * 依恋回避均分A=（1，3，5，7……35）/18即基数项的平均得分； 单数
    * 依恋焦虑维度B=（2，4，6，……36）/18 即偶数项的平均得分  双数
    * M1安全型=A×3.2893296+B×5.4725318-11.5307833
    * M2恐惧型=A×7.2371075+B×8.1776448-32.3553266
    * M3倾注型=A×3.9246754+B×9.7102446-28.4573220
    * M4轻视型（或回避冷漠型）=A×7.3654621+B×4.9392039-22.2281088
    * 哪个得分高即为哪个型。
    * */ 
  //  单数平均值
  let singlarAverage = BigNumber(scores.singularSum / 18)
  let enevAverage = BigNumber(scores.evenSum / 18)
  //  安全 对应 安全型依附4
  let safeType = singlarAverage.multipliedBy(BigNumber(3.2893296)).plus(enevAverage.multipliedBy(BigNumber(5.4725318))).minus(11.5307833).toNumber()
  //  恐惧 对应 逃避型依附2
  let fearType = singlarAverage.multipliedBy(BigNumber(7.2371075)).plus(enevAverage.multipliedBy(BigNumber(8.1776448))).minus(32.3553266).toNumber()
  // 倾注型 对应 焦虑型依附1
  let obsessType = singlarAverage.multipliedBy(BigNumber(3.9246754)).plus(enevAverage.multipliedBy(BigNumber(9.7102446))).minus(28.4573220).toNumber()
  // 轻视 对应 矛盾型依附3
  let despiseType = singlarAverage.multipliedBy(BigNumber(7.3654621)).plus(enevAverage.multipliedBy(BigNumber(4.9392039))).minus(22.2281088).toNumber()

  let arr = [
    { type: 4, value: safeType },
    { type: 2, value: fearType },
    { type: 1, value: obsessType },
    { type: 3, value: despiseType },
  ]
  arr.forEach(item => {
    if (item.value > maxVal.value.value) {
      maxVal.value = item
    }
  })

}
// 支付
let onPayment = () => {
  onPay().then(() => {
    console.log('支付成功')
    isPay.value = true
    setTimeout(() => {
      console.log(maxVal.value.type)
      router.replace('/test/result?type=' + maxVal.value.type)
    }, 4000)
  })
}
let isPay = ref(false)
</script>
<style lang="scss" scoped src="./index.scss">
</style>